package com.fancy.learncenter.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.BaseBean;
import com.fancy.learncenter.bean.CartoonAnswerKeysBean;
import com.fancy.learncenter.bean.CartoonCommitAnswerBean;
import com.fancy.learncenter.bean.CartoonGetAnswerResultBean;
import com.fancy.learncenter.bean.CartoonGetHomeAnswerBean;
import com.fancy.learncenter.bean.CartoonMediaBean;
import com.fancy.learncenter.bean.CartoonStemsBean;
import com.fancy.learncenter.bean.CartoonTextsBean;
import com.fancy.learncenter.bean.QuestionVOsBean;
import com.fancy.learncenter.common.JumpIntentKey;
import com.fancy.learncenter.common.MAudioPlayer;
import com.fancy.learncenter.common.MyApplication;
import com.fancy.learncenter.net.CustomNetCallBack;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.adapter.CartoonQuestionImageAdapter;
import com.fancy.learncenter.ui.callback.AlbumImpl;
import com.fancy.learncenter.ui.view.CartoonAnalysisPopu;
import com.fancy.learncenter.ui.view.GridSpacingItemDecoration;
import com.fancy.learncenter.utils.CartoonToastUtils;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

import static com.fancy.learncenter.common.JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_ANALYSIS;
import static com.fancy.learncenter.common.JumpIntentKey.RIGHT_NUM;

/**
 * 语法类-听音选图（两个图片）
 */
public class GrammarListenChooseImageFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @Bind(R.id.commit_image)
    ImageView commitImage;
    @Bind(R.id.voice_image)
    ImageView voiceImage;
    @Bind(R.id.previous_question)
    ImageView previousQuestion;
    @Bind(R.id.next_question)
    ImageView nextQuestion;
    @Bind(R.id.bottom_layout)
    RelativeLayout bottomLayout;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.question_name)
    TextView questionName;
    @Bind(R.id.rootView)
    RelativeLayout rootView;

    // TODO: Rename and change types of parameters
    private int currentIndex;
    private int totalNum;
    boolean isAgain;
    ArrayList<QuestionVOsBean> questionList;
    private OnGrammarListenChooseListener mListener;
    private List<CartoonMediaBean> images = new ArrayList<>();
    private String standardAnswerId;
    private String audioUrl;
    private String titleStr;
    private String questionNameStr;
    private JumpIntentKey.QUESTION_ENTER_TYPE type;
    private String homePackageId;
    private Handler handler = new Handler();
    private int state;
    private List<CartoonCommitAnswerBean> commitAnswerBeanList;
    private QuestionVOsBean questionVOsBean;
    private String studentHomeworkId;
    private Fragment currentFragment;
    private String analysisText;
    private CartoonQuestionImageAdapter adapter;
    private JumpIntentKey.CARTOON_BUTTON_STATUS buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_GRAY;
    private String writeAnswerId;
    private CartoonGetHomeAnswerBean homeAnswerBean;
    private MAudioPlayer audioPlayer;
    private String lessonNameStr;
    private String unitNameStr;

    public GrammarListenChooseImageFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment GrammarListenChooseImageFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static GrammarListenChooseImageFragment newInstance(ArrayList<QuestionVOsBean> list, int currentIndex, int totalNum, JumpIntentKey.QUESTION_ENTER_TYPE type, String homePackageId, String studentHomeworkId, String lessonNameStr, String unitNameStr) {
        GrammarListenChooseImageFragment fragment = new GrammarListenChooseImageFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, currentIndex);
        args.putInt(ARG_PARAM2, totalNum);
        args.putSerializable(JumpIntentKey.QUESTION_ENTER, type);
        args.putParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY, list);
        args.putString(JumpIntentKey.HOMEWORK_PACKAGE_ID, homePackageId);
        args.putString(JumpIntentKey.STUDENTHOMEWORKID, studentHomeworkId);
        args.putString(JumpIntentKey.LESSON_NAME, lessonNameStr);
        args.putString(JumpIntentKey.UNIT_NAME, unitNameStr);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        currentFragment = this;
        if (getArguments() != null) {
            currentIndex = getArguments().getInt(ARG_PARAM1);
            totalNum = getArguments().getInt(ARG_PARAM2);
            type = (JumpIntentKey.QUESTION_ENTER_TYPE) getArguments().getSerializable(JumpIntentKey.QUESTION_ENTER);
            questionList = getArguments().getParcelableArrayList(JumpIntentKey.QUSETION_BANK_LIST_KEY);
            homePackageId = getArguments().getString(JumpIntentKey.HOMEWORK_PACKAGE_ID);
            studentHomeworkId = getArguments().getString(JumpIntentKey.STUDENTHOMEWORKID);
            lessonNameStr = getArguments().getString(JumpIntentKey.LESSON_NAME);
            unitNameStr = getArguments().getString(JumpIntentKey.UNIT_NAME);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_grammar_listen_choose, container, false);
        ButterKnife.bind(this, view);

        initData();
        initClick();
        return view;
    }

    private void initData() {


        if (questionList != null && questionList.size() > 0) {
            questionVOsBean = questionList.get(currentIndex);
            images = questionVOsBean.getOptions().getImages();
            CartoonAnswerKeysBean answerKeysBean = questionVOsBean.getAnswerKeys();
            if (answerKeysBean != null) {
                List<CartoonTextsBean> answerKeysList = answerKeysBean.getTexts();
                if (answerKeysList != null && answerKeysList.size() > 0) {

                    analysisText = answerKeysList.get(0).getValue();
                }
            }

            CartoonStemsBean stemsBean = questionVOsBean.getStems();
            if (stemsBean != null) {
                List<CartoonTextsBean> textsBeanList = stemsBean.getTexts();
                if (textsBeanList != null && textsBeanList.size() > 0) {
                    questionNameStr = textsBeanList.get(0).getValue();
                    if (!TextUtils.isEmpty(questionNameStr)) {
                        questionName.setText(questionNameStr);
                        questionName.setVisibility(View.VISIBLE);
                    } else {
                        questionName.setVisibility(View.GONE);
                    }
                } else {
                    questionName.setVisibility(View.GONE);
                }
            }

            onButtonPressed(currentIndex + 1, totalNum, questionVOsBean.getConstructionNameCn());
            initRecycleView();

            List<CartoonMediaBean> audioList = questionVOsBean.getStems().getAudios();
            if (audioList != null && audioList.size() > 0) {
                audioUrl = audioList.get(0).getPlayLink();
            }
            List<CartoonTextsBean> answerList = questionVOsBean.getAnswers().getTexts();
            if (answerList != null && answerList.size() > 0) {

                if (!TextUtils.isEmpty(answerList.get(0).getValue())) {
                    standardAnswerId = answerList.get(0).getValue();
                }
            }

        }

    }


    private void initRecycleView() {

        GridSpacingItemDecoration itemDecoration = new GridSpacingItemDecoration(2, Utils.dip2pix(getActivity(), 40), false);
        GridLayoutManager manager = new GridLayoutManager(getActivity(), 2);
        manager.setOrientation(GridLayoutManager.VERTICAL);
        recyclerView.addItemDecoration(itemDecoration);
        recyclerView.setLayoutManager(manager);
        adapter = new CartoonQuestionImageAdapter(getActivity(), type, images);
        recyclerView.setAdapter(adapter);

        adapter.setListener(new AlbumImpl() {
            @Override
            public void onClick(int position) {
                if (type != JumpIntentKey.QUESTION_ENTER_TYPE.WORK_REPORT) {
                    images.get(position).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_CHOOSE);
                    buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_LIGHT;
                    Utils.notifyButtonBg(buttonStatus, commitImage);
                    writeAnswerId = String.valueOf(images.get(position).getId());

                    for (int i = 0; i < images.size(); i++) {
                        if (i != position) {
                            images.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_DEFAULT);
                        }
                    }

                    adapter.notifyDataSetChanged();
                }
            }
        });
    }


    private void initClick() {
        commitImage.setOnClickListener(this);
        commitImage.setEnabled(false);
        previousQuestion.setOnClickListener(this);
        nextQuestion.setOnClickListener(this);
        voiceImage.setOnClickListener(this);


        switch (type) {
            case DO_WORK:
            case CONTINUE_WORK:
                previousQuestion.setVisibility(View.GONE);
                nextQuestion.setVisibility(View.GONE);
                break;
            case DO_IT_AGAIN:
                previousQuestion.setVisibility(View.GONE);
                nextQuestion.setVisibility(View.GONE);
                break;
            case TEACHER_WORK_PREVIEW:
                adapter.setListener(new AlbumImpl() {
                    @Override
                    public void onClick(int position) {

                    }
                });
                rootView.setVisibility(View.GONE);
                seeAnswer();
                break;
            case WORK_REPORT:
                previousQuestion.setVisibility(View.VISIBLE);
                nextQuestion.setVisibility(View.VISIBLE);
                if (currentIndex == 0) {
                    previousQuestion.setVisibility(View.GONE);
                }
                if (currentIndex == totalNum - 1) {
                    nextQuestion.setVisibility(View.GONE);
                }
                getWorkReportAnswer();
                break;
            case HAS_CORRECTED:
            case NOT_CORRECTED:
            case ERROR_KINDS:
                previousQuestion.setVisibility(View.VISIBLE);
                nextQuestion.setVisibility(View.VISIBLE);
                if (currentIndex == 0) {
                    previousQuestion.setVisibility(View.GONE);
                }
                if (currentIndex == totalNum - 1) {
                    nextQuestion.setVisibility(View.GONE);
                }
                break;
        }
    }

    /**
     * 获取客观题答案
     */
    private void getWorkReportAnswer() {

        Map<String, Object> map = new HashMap<>();
        map.put("packageId", homePackageId);
        map.put("classId", MyApplication.classIDStr);
        map.put("questionId", questionVOsBean.getQuestionId());

        HttpMehtod.getInstance().cartoonGetHomeAnswer(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                BaseBean<CartoonGetAnswerResultBean> baseBean = Utils.fromJsonObject(NetUtil.getResResult(responseBodyResponse), CartoonGetAnswerResultBean.class);
                CustomNetCallBack callBack = new CustomNetCallBack(getContext(), baseBean);
                callBack.setCallBack(new CustomNetCallBack.NetCallBack<CartoonGetAnswerResultBean>() {
                    @Override
                    public void success(CartoonGetAnswerResultBean dataBean) {

                        if (dataBean != null) {
                            homeAnswerBean = dataBean.getResult();
                            List<CartoonCommitAnswerBean> answerResourceList = homeAnswerBean.getAnswerResourceList();
                            CartoonCommitAnswerBean answerBean = answerResourceList.get(0);
                            String commitAnswerId = answerBean.getQuestionResourceId();
                            for (CartoonMediaBean bean : images) {
                                if (String.valueOf(bean.getId()).equals(commitAnswerId)) {

                                    if (String.valueOf(standardAnswerId).equals(commitAnswerId)) {

                                        bean.setStatus(JumpIntentKey.OPTION_STATUS.STATUS_RIGHT);
                                        commitImage.setVisibility(View.INVISIBLE);
                                    } else {
                                        commitImage.setVisibility(View.VISIBLE);
                                        buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
                                        bean.setStatus(JumpIntentKey.OPTION_STATUS.STATUS_WRONG);
                                        Utils.notifyButtonBg(buttonStatus, commitImage);
                                    }
                                }
                                adapter.notifyDataSetChanged();

                                break;
                            }
                        }
                    }

                    @Override
                    public void fail(String errorCode) {


                    }
                }).dealData();
            }
        });

    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(int currentIndex, int totalNum, String title) {
        if (mListener != null) {
            mListener.onGrammarListenChoose(currentIndex, totalNum, title);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnGrammarListenChooseListener) {
            mListener = (OnGrammarListenChooseListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.voice_image:
                Utils.playOrPauseAudio(audioPlayer, audioUrl, voiceImage);
                break;


            case R.id.commit_image:
                switch (buttonStatus) {

                    case STATUS_LIGHT:
                        judgeRightOrWrong();
                        switch (type) {
                            case DO_WORK:
                            case CONTINUE_WORK:
                            case DO_IT_AGAIN:
                            case HAS_CORRECTED:
                                commiteAnswer();
                                break;
                            case NOT_CORRECTED:
                            case ERROR_KINDS:
                                if (state == 1) {
                                    errorQuestionCommitAnswer();
                                }
                                break;
                        }
                        break;
                    case STATUS_SEE_ANSWER:
                        seeAnswer();
                        break;
                    case STATUS_ANALYSIS:
                        CartoonAnalysisPopu popu = new CartoonAnalysisPopu(getActivity(), analysisText, commitImage);
                        popu.showPopupWindow();
                        break;
                }

                break;

            case R.id.previous_question:
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                Utils.switchFragment(getActivity(), transaction, questionList, currentIndex - 1, R.id.fg_container, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
                break;
            case R.id.next_question:
                FragmentTransaction transaction2 = getFragmentManager().beginTransaction();
                Utils.switchFragment(getActivity(), transaction2, questionList, currentIndex + 1, R.id.fg_container, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);

                break;

        }
    }

    private void seeAnswer() {

        for (int i = 0; i < images.size(); i++) {

            if (String.valueOf(standardAnswerId).equals(String.valueOf(images.get(i).getId()))) {

                images.get(i).setStatus(JumpIntentKey.OPTION_STATUS.STATUS_RIGHT);
            }
        }
        buttonStatus = STATUS_ANALYSIS;
        adapter.notifyDataSetChanged();
        Utils.notifyButtonBg(buttonStatus, commitImage);
    }


    private void judgeRightOrWrong() {
        if (standardAnswerId.equals(writeAnswerId)) {
            state = 1;
            RIGHT_NUM++;
            CartoonToastUtils.show(true);
        } else {
            state = 0;
            CartoonToastUtils.show(false);
        }
    }

    private void jumpToFragement(final int index) {
        FragmentManager manager = getFragmentManager();
        final FragmentTransaction transaction = manager.beginTransaction();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Utils.switchFragment(getActivity(), transaction, questionList, index, R.id.fg_container, type, homePackageId, studentHomeworkId, lessonNameStr, unitNameStr);
            }
        }, 1500);
    }

    /**
     * 错题中心 -- 未订正 错题分类
     */
    private void errorQuestionCommitAnswer() {
        Map<String, Object> map = new HashMap<>();
        map.put("studentHomeworkDoneDetailId", questionVOsBean.getStudentHomeworkDoneDetailId());
        HttpMehtod.getInstance().cartoonCorrectErrorQuestion(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {

                jumpToFragement(currentIndex + 1);

            }
        });
    }


    /**
     * 提交答案
     */
    private void commiteAnswer() {
        commitAnswerBeanList = new ArrayList<>();
        CartoonCommitAnswerBean answerBean = new CartoonCommitAnswerBean();
        answerBean.setQuestionResourceId(writeAnswerId);
        answerBean.setResourceType("0");
        commitAnswerBeanList.add(answerBean);

        Map<String, Object> map = new HashMap<>();
        map.put("classId", MyApplication.classIDStr);
        map.put("state", state);
        map.put("homeworkPackageId", homePackageId);
        map.put("objectQuestionId", questionVOsBean.getQuestionId());
        map.put("answerResourceList", commitAnswerBeanList);
        map.put("studentHomeworkId", studentHomeworkId);
        HttpMehtod.getInstance().cartoonCommitHomeAnsers(map, new CustomNetSubscriber(getActivity()) {
            @Override
            public void onNext(Response<ResponseBody> responseBodyResponse) {


                switch (type) {
                    case HAS_CORRECTED:
                        if (state == 1) {
                            jumpToFragement(currentIndex + 1);
                        } else {
                            buttonStatus = JumpIntentKey.CARTOON_BUTTON_STATUS.STATUS_SEE_ANSWER;
                            Utils.notifyButtonBg(buttonStatus, commitImage);
                        }
                        break;
                    case DO_IT_AGAIN:
                    case DO_WORK:
                    case CONTINUE_WORK:
                        jumpToFragement(currentIndex + 1);
                        break;
                }


            }
        });

    }


    /**
     *
     */
    public interface OnGrammarListenChooseListener {
        // TODO: Update argument type and name
        void onGrammarListenChoose(int currentIndex, int totalNum, String title);
    }
}
